import { useRoutes } from "react-router-dom";
import SystemLayout from "@/layout/SystemLayout";
import Login from "@/pages/login/login";
import React, { Suspense, lazy, type ReactNode, useEffect, useState, useMemo } from "react"; // 导入 React 和 useMemo
import type { ExtendedRouteObject } from "@/types/route";
import remainingRoutes from "@/router/remainingRoutes";
import store from "@/store"; // 导入store以获取用户信息
import type { UserInfoDTO } from "@/types/user";
import { useSelector } from "react-redux";
import type { RootState } from "@/store";
import NotFound from "@/pages/notfound";

// -------------------------- 1. 补充：convertComponentPathToElement 函数（关键缺失） --------------------------
const convertComponentPathToElement = (routes: ExtendedRouteObject[]): ExtendedRouteObject[] => {
  return routes.map(route => {
    // 基础属性复制，避免修改原对象
    const baseRoute = { ...route };

    // 处理 element：将 componentPath 转为懒加载的 element
    const elementConfig = baseRoute.componentPath 
      ? { element: withSuspense(baseRoute.componentPath) } 
      : {};

    // 处理 children：仅普通路由（非索引路由）递归转换，索引路由禁止 children
    let childrenConfig = {};
    if (!baseRoute.index && baseRoute.children) {
      childrenConfig = {
        children: convertComponentPathToElement(baseRoute.children)
      };
    }

    return {
      ...baseRoute,
      ...elementConfig,
      ...childrenConfig,
      componentPath: undefined, // 删除冗余的 componentPath，避免类型混淆
      ...(baseRoute.index && { children: undefined }) // 强制索引路由无 children
    };
  });
};

// -------------------------- 2. 懒加载高阶函数（保持不变，确保返回 ReactNode） --------------------------
const withSuspense = (componentPath?: string): ReactNode => {
  if (!componentPath) {
    return <div>该路由无对应组件</div>;
  }
  const LazyComponent = lazy(async () => {
    return import(`../pages/${componentPath}`).catch((error) => {
      console.error(`组件加载失败: ${componentPath}`, error);
      return Promise.resolve({ default: () => <div>组件加载失败: ${componentPath}</div> });
    });
  });

  return (
    <Suspense fallback={<div>Loading...</div>}>
      <LazyComponent />
    </Suspense>
  );
};

// -------------------------- 3. 路由过滤函数（外部正确实现，保持不变） --------------------------
const filterRoutesByRole = (routes: ExtendedRouteObject[], userType: string): ExtendedRouteObject[] => {
  return routes
    .filter(route => !route.accessRoles || route.accessRoles.includes(userType))
    .map(route => {
      const baseRoute = { ...route };
      let childrenConfig = {};

      // 仅普通路由处理 children，索引路由跳过
      if (!baseRoute.index && baseRoute.children) {
        childrenConfig = {
          children: filterRoutesByRole(baseRoute.children, userType)
        };
      }

      return {
        ...baseRoute,
        ...childrenConfig,
        ...(baseRoute.index && { children: undefined }) // 强制索引路由无 children
      };
    });
};

// -------------------------- 4. 动态路由配置（使用 useRoutes） --------------------------
const createRouteConfig = (userType: string) => {
  // 过滤路由
  const filteredRemainingRoutes = filterRoutesByRole(remainingRoutes, userType);

  // 基础路由配置
  const routeConfig: ExtendedRouteObject[] = [
    {
      path: "/login",
      element: <Login />,
    },
    {
      path: "/",
      element: <SystemLayout />,
      children: [
        {
          index: true, // 索引路由，无 children
          element: withSuspense("home/home"),
        },
        ...filteredRemainingRoutes, // 直接使用过滤后的路由，不在这里转换
      ],
    },
    {
      path:"/404",
      element: <NotFound />,
    },
    {
      path: "*", // 404 路由
      element: <NotFound />,
    }
  ];

  // 只在最后调用一次转换函数，处理所有路由
  return convertComponentPathToElement(routeConfig);
};

// 动态路由组件
export const DynamicRoutes = () => {
  // 从 Redux store 获取用户类型
  const userType = useSelector((state: RootState) => state.userSlice.userInfo?.userType);
  // 确保userType有默认值
  const safeUserType = userType || 'merchant'; // 默认使用merchant角色
  
  useEffect(() => {
    console.log('用户类型:', safeUserType);
  }, [safeUserType]);
  
  // 计算路由配置 - 使用useMemo确保只在userType变化时重新计算
  const routes = React.useMemo(() => {
    console.log('生成新路由配置');
    return createRouteConfig(safeUserType);
  }, [safeUserType]);
  
  // 使用 useRoutes 钩子创建路由
  const element = useRoutes(routes);
  
  // 确保总是有返回值
  if (!element) {
    console.warn('路由未匹配');
    return <NotFound />;
  }
  
  return element;
};

// 导出默认的路由组件
export default DynamicRoutes;